package com.foogui.demo.transaction;

import com.alibaba.nacos.api.utils.StringUtils;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

public class Producer {

    public static void main(String[] args) throws Exception {
        //1.创建消息生产者producer，并指定生产者组名
        TransactionMQProducer producer = new TransactionMQProducer("transactionGroup5");
        //2.指定Nameserver地址
        producer.setNamesrvAddr("localhost:9876");

        //添加事务的监听器
        producer.setTransactionListener(new TransactionListener() {
            /**
             * 执行本地事务
             * @param msg
             * @param arg
             * @return
             */
            @Override
            public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
                System.out.println("本地事务执行");
                if (StringUtils.equals("TAGA", msg.getTags())) {
                    return LocalTransactionState.COMMIT_MESSAGE;
                } else if (StringUtils.equals("TAGB", msg.getTags())) {
                    return LocalTransactionState.ROLLBACK_MESSAGE;
                } else if (StringUtils.equals("TAGC", msg.getTags())) {
                    return LocalTransactionState.UNKNOW;
                }
                return null;
            }

            /**
             * 事务状态的回查
             * @param msg
             * @return
             */
            @Override
            public LocalTransactionState checkLocalTransaction(MessageExt msg) {
                System.out.println("事务消息回查, tag = " + msg.getTags());
                return LocalTransactionState.COMMIT_MESSAGE;
            }
        });



        String[] tags = {"TAGA", "TAGB", "TAGC"};

        //3.启动producer
        producer.start();
        for (int i = 0; i < 3; i++) {
            //4.创建消息对象，指定主题Topic、Tag和消息体
            //arg1：消息的topic
            //arg2：消息的Tag
            //arg3：消息主体
            Message msg = new Message("TransactionTopic", tags[i], ("Hello World" + i).getBytes());
            //5.发送同步消息
            SendResult result = producer.sendMessageInTransaction(msg, null);
            //发送状态
            SendStatus status = result.getSendStatus();
            System.out.println("发送结果：" + result + ", 发送时间 = " +
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
            TimeUnit.SECONDS.sleep(1);
        }
        //6.关闭生产者producer
//        producer.shutdown();
    }

}

